package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Slf4j
@Api(tags = "用户地址簿")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    @GetMapping("/list")
    @ApiOperation(value = "获取用户地址簿列表")
    public Result<List<AddressBook>> list() {
        log.info("获取用户地址簿列表");
        AddressBook addressBook = new AddressBook();
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        List<AddressBook> list = addressBookService.list(addressBook);
        return Result.success(list);
    }

    @PostMapping
    @ApiOperation(value = "新增用户地址簿")
    public Result save(@RequestBody AddressBook addressBook) {
        log.info("新增用户地址簿:{}", addressBook);
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBookService.save(addressBook);
        return Result.success();
    }

    @PutMapping("/default")
    @ApiOperation(value = "设置默认地址簿")
    public Result setDefault(@RequestBody AddressBook addressBook) {
        log.info("设置默认地址簿:{}", addressBook);
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBookService.setDefault(addressBook);
        return Result.success();
    }

    @GetMapping("/default")
    @ApiOperation(value = "获取默认地址簿")
    public Result<AddressBook> getDefault(@RequestBody AddressBook addressBook) {
        log.info("获取默认地址簿:{}", addressBook);
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        List<AddressBook> list = addressBookService.getDefault(addressBook);
        if (list != null && list.size() == 1) {
            return Result.success(list.get(0));
        }
        return Result.error("未找到默认地址簿");
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询地址簿")
    public Result<AddressBook> getById(@PathVariable Long id) {
        log.info("根据id查询地址簿:{}", id);
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }

    @PutMapping
    @ApiOperation(value = "修改用户地址簿")
    public Result update(@RequestBody AddressBook addressBook) {
        log.info("修改用户地址簿:{}", addressBook);
        addressBookService.update(addressBook);
        return Result.success();
    }
    @DeleteMapping
    @ApiOperation(value = "删除用户地址簿")
    public Result delete(@RequestParam Long id) {
        log.info("删除用户地址簿:{}", id);
        addressBookService.delete(id);
        return Result.success();
    }
}
